package com.bdmc.smokesensor.controller.api;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import com.alibaba.fastjson.JSONObject;
import com.bdmc.smokesensor.Utils.CommonUtil;
import com.bdmc.smokesensor.Utils.Constants;
import com.bdmc.smokesensor.Utils.DateUtil;
import com.bdmc.smokesensor.Utils.Msg;
import com.bdmc.smokesensor.Utils.MyWebConfig;
import com.bdmc.smokesensor.Utils.ResultUtil;
import com.bdmc.smokesensor.Utils.WebTokenUtil;
import com.bdmc.smokesensor.Utils.redis.RedisUtil;
import com.bdmc.smokesensor.Utils.wechatsdk.WeChatUtil;
import com.bdmc.smokesensor.annotation.AuthIgnore;
import com.bdmc.smokesensor.controller.BaseController;
import com.bdmc.smokesensor.entity.Smk_Alarm;
import com.bdmc.smokesensor.entity.Smk_Buildings;
import com.bdmc.smokesensor.entity.Smk_Devices;
import com.bdmc.smokesensor.entity.Sys_ValidateCode;
import com.bdmc.smokesensor.iservices.ISmk_AlarmService;
import com.bdmc.smokesensor.iservices.ISmk_BuildingsService;
import com.bdmc.smokesensor.iservices.ISmk_DevicesService;
import com.bdmc.smokesensor.iservices.ISys_ValidateCodeService;
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping(value = "/wechat/customer")
public class CustomerController extends BaseController {

    @Autowired
    public RedisUtil _redis;

    @Autowired
    private ISys_ValidateCodeService _codeSvs;

    @Autowired
    private ISmk_BuildingsService _buildSvs;

    @Autowired
    private ISmk_DevicesService _deviceSvs;

    @Autowired
    private MyWebConfig _webconfig;

    @Autowired
    private ISmk_AlarmService _alarmSvs;

    @AuthIgnore
    @PostMapping(value = "/verifycode")
    public Msg verifyCode(@RequestBody Map<String, Object> map) {
        String mobile = map.get("mobile").toString();
        int purpose = Integer.valueOf(map.get("purpose").toString());
        if (mobile == null || mobile.isEmpty()) {
            return ResultUtil.error(-1, "手机号不能为空。");
        }
        if (purpose <= 0) {
            return ResultUtil.error(-1, "参数不正确。");
        }
        Sys_ValidateCode code = _codeSvs.findByMobileAndIsUsedAndPurpose(mobile, false, purpose);
        if (code != null) {// 说明是再次发送获取验证码，判断间隔时间
            Date now = new Date();
            if (code.getSendTime() != null
                    && DateUtil.dateAddMinute(code.getSendTime(), Constants.INTERVAL).before(now)) {// 时间间隔正常，可以再次发送本条验证码
                String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);// 生成短信验证码
                SmsSingleSender ssender = new SmsSingleSender(Constants.SHORTMSGAPPID, Constants.SHORTMSGAPPKEY);
                String[] params = { verifyCode, String.valueOf(Constants.EXPIREMIN) };
                try {
                    SmsSingleSenderResult sendResult = ssender.sendWithParam("86", mobile, 195696, params, "", "", "");
                    if (sendResult.result != 0) {
                        return ResultUtil.error(-1, "短信发送失败，请联系客服人员。");
                    }
                } catch (Exception e) {
                    logger.error(e.getMessage());
                    return ResultUtil.error(-1, "短信发送失败，请联系客服人员。");
                }
                List<Smk_Buildings> shops = _buildSvs.findByManagerMobile(mobile);
                code.setValidateCode(verifyCode);
                code.setStartTime(now);
                code.setEndTime(DateUtil.dateAddMinute(now, Constants.EXPIREMIN));
                code.setSendTime(now);
                _codeSvs.save(code);
                Map<String, Object> resultMap = new HashMap<String, Object>();
                resultMap.put("sendStat", "0");
                if (shops.size() > 0) {
                    resultMap.put("addr", shops.get(0).getAddr());
                    resultMap.put("shopName", shops.get(0).getName());
                    resultMap.put("manageName", shops.get(0).getManagerName());
                }
                return ResultUtil.success(resultMap);
            } else {
                return ResultUtil.error(-1, "请求时间过短 ，请稍后再试！");
            }
        } else {
            Date now = new Date();
            String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);// 生成短信验证码
            SmsSingleSender ssender = new SmsSingleSender(Constants.SHORTMSGAPPID, Constants.SHORTMSGAPPKEY);
            String[] params = { verifyCode, String.valueOf(Constants.EXPIREMIN) };
            try {
                SmsSingleSenderResult sendResult = ssender.sendWithParam("86", mobile, 195696, params, "", "", "");
                if (sendResult.result != 0) {
                    return ResultUtil.error(-1, "短信发送失败，请联系客服人员。");
                }
            } catch (Exception e) {
                logger.error(e.getMessage());
                return ResultUtil.error(-1, "短信发送失败，请联系客服人员。");
            }
            List<Smk_Buildings> shops = _buildSvs.findByManagerMobile(mobile);
            Sys_ValidateCode newCode = new Sys_ValidateCode();
            newCode.setMobile(mobile);
            newCode.setPurpose(purpose);
            newCode.setUsed(false);
            newCode.setValidateCode(verifyCode);
            newCode.setStartTime(now);
            newCode.setEndTime(DateUtil.dateAddMinute(now, Constants.EXPIREMIN));
            newCode.setSendTime(now);
            _codeSvs.save(newCode);
            Map<String, Object> resultMap = new HashMap<String, Object>();
            resultMap.put("sendStat", "0");
            if (shops.size() > 0) {
                resultMap.put("addr", shops.get(0).getAddr());
                resultMap.put("shopName", shops.get(0).getName());
                resultMap.put("manageName", shops.get(0).getManagerName());
            }
            return ResultUtil.success(resultMap);

        }
    }

    @AuthIgnore
    @PostMapping(value = "/bind")
    public Msg bind(@RequestBody Map<String, Object> map) {
        String mobile = String.valueOf(map.get("mobile"));
        String validateCode = String.valueOf(map.get("validateCode"));
        Integer purpose = Integer.valueOf(String.valueOf(map.get("purpose")));
        String openid = String.valueOf(map.get("openid"));
        String wxImage = String.valueOf(map.get("wxImage"));
        String wxName = String.valueOf(map.get("wxName"));
        String shopName = String.valueOf(map.get("shopName"));
        String addr = String.valueOf(map.get("addr"));
        String managerName = String.valueOf(map.get("managerName"));

        if (mobile == null || validateCode == null || purpose == null || openid == null || wxName == null) {
            return ResultUtil.error(-1, "参数错误");
        }
        Sys_ValidateCode vcode = _codeSvs.findByValidateCodeAndMobileAndIsUsedAndPurpose(validateCode, mobile, false,
                purpose);
        Date now = new Date();
        if (vcode == null || vcode.endTime.before(now)) {
            return ResultUtil.error(-1, "验证码不存在或已过期，请重新获取。");
        }
        List<Smk_Buildings> shops = _buildSvs.findByManagerMobile(mobile);
        Boolean bindResult = false;
        String token = "";
        Map<String, Object> respMap = new HashMap<>();
        if (shops.size() <= 0) {// 新增
            Smk_Buildings bd = new Smk_Buildings();
            bd.setAddr(addr);
            bd.setName(shopName);
            bd.setManagerMobile(mobile);
            bd.setDepartmentId(1);
            bd.setManagerName(managerName);
            bd.setOpenid(openid);
            bd.setWxImage(wxImage);
            bd.setWxName(wxName);
            bd.setSmkGroupCompanyId(0);
            bd.setJoinDate(new Date());
            bd.setDel(false);
            Smk_Buildings db_build = _buildSvs.save(bd);
            bindResult = db_build.getId() > 0;
            token = WebTokenUtil.createJWT(db_build.getId(), db_build.getOpenid(), db_build.getDepartmentId(),
                    db_build.getWxName(), 36000000);
        } else {// 绑定所有同手机号店铺
            for (Smk_Buildings b : shops) {
                b.setOpenid(openid);
                b.setWxImage(wxImage);
                b.setWxName(wxName);
            }
            bindResult = _buildSvs.batchSave(shops).size() > 0;
            token = WebTokenUtil.createJWT(shops.get(0).getId(), shops.get(0).getOpenid(),
                    shops.get(0).getDepartmentId(), shops.get(0).getWxName(), 36000000);
        }
        if (bindResult) {// 成功则使用验证码
            vcode.setUsed(true);
            _codeSvs.save(vcode);
            respMap.put("openid", openid);
            respMap.put("wxName", wxName);
            respMap.put("wxImage", wxImage);
            respMap.put("mobile", mobile);
            respMap.put("token", token);
            return ResultUtil.success(respMap);
        } else {
            return ResultUtil.error(-1, "服务器异常！");
        }
    }

    @PostMapping(value = "/getsign")
    public Msg getSign(@RequestBody Map<String, Object> map) {
        String url = String.valueOf(map.get("url"));
        if (url != null && url.length() > 0) {
            JSONObject sign = WeChatUtil.getSign(url);
            return ResultUtil.success(sign);
        }
        return ResultUtil.error(-1, "参数错误！");
    }

    // 获取商户信息
    @PostMapping(value = "/shops")
    public Msg getShops() {
        String openid = getLoginName();
        if (StringUtils.isEmpty(openid)) {
            return ResultUtil.error(-1, "openid为空");
        }
        List<Smk_Buildings> shops = _buildSvs.findByOpenid(openid);
        return ResultUtil.success(shops);
    }

    @PostMapping(value = "/shopbyid")
    public Msg getShopsById(@RequestBody Map<String, Integer> map) {
        int id = map.get("id");
        Smk_Buildings shop = _buildSvs.findOneById(id);
        return ResultUtil.success(shop);
    }

    // 添加紧急联系人
    @PostMapping(value = "/addnotifier")
    public Msg addNotifyier(@RequestBody Map<String, Object> map) {
        String notify = String.valueOf(map.get("alarmNotifier"));
        int id = Integer.valueOf(String.valueOf(map.get("id")));
        if (id <= 0) {
            return ResultUtil.error(-1, "参数错误！");
        }
        Smk_Buildings buildings = _buildSvs.findOneById(id);
        // notify = buildings.getAlarmNotifier()+"|"+notify;
        buildings.setAlarmNotifier(notify);
        _buildSvs.save(buildings);
        return ResultUtil.success();
    }

    // 获取设备信息
    @PostMapping(value = "/devices")
    public Msg getSevices(@RequestBody Map<String, Integer> map) {
        int smkBuildingId = map.get("smkBuildingId");
        List<Smk_Devices> devices = _deviceSvs.findBySmkBuildingId(smkBuildingId);
        return ResultUtil.success(devices);
    }

    @AuthIgnore
    @PostMapping("/dutyletter")
    public Msg dutyLetter(@RequestBody Map<String, Object> map) {
        int id = Integer.valueOf(map.get("id").toString());
        String media_id = String.valueOf(map.get("media_id"));
        String path = WeChatUtil.downloadImage(media_id);
        if (!StringUtils.isEmpty(path)) {
            Smk_Buildings b = _buildSvs.findOneById(id);
            if (b == null) {
                return ResultUtil.error(-1, "店铺不存在！");
            }
            b.setDutyLetter(path);
            _buildSvs.save(b);
            return ResultUtil.success(path);
        }
        return ResultUtil.error(-1, "图片上传失败。");
    }

    @AuthIgnore
    @PostMapping("/dutyletter1")
    public Msg upload(@RequestParam("dutyletter") MultipartFile multipartFile, @RequestBody Map<String, Integer> map) {
        int id = map.get("id");
        if (id <= 0) {
            return ResultUtil.error(-1, "参数错误！");
        }
        Smk_Buildings b = _buildSvs.findOneById(id);
        if (b == null) {
            return ResultUtil.error(-1, "店铺不存在！");
        }
        if (multipartFile.isEmpty() || StringUtils.isEmpty(multipartFile.getOriginalFilename())) {
            return ResultUtil.error(-1, "参数错误！");
        }
        String contentType = multipartFile.getContentType();
        if (!contentType.contains("")) {
            return ResultUtil.error(-1, "参数错误！");
        }
        String root_fileName = multipartFile.getOriginalFilename();
        logger.info("上传图片:name={},type={}", root_fileName, contentType);

        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateString = formatter.format(new Date());

        String fileName = dateString + root_fileName;

        File path = new File(_webconfig.getExportPath());
        if (!path.exists()) {
            path.mkdir();
        }

        String filePath;
        try {
            filePath = "/image/" + CommonUtil.saveImg(multipartFile, path.getAbsolutePath() + "/image/", fileName);
            logger.info("图片保存路径={}", filePath);
            b.setDutyLetter(filePath);
            _buildSvs.save(b);
            return ResultUtil.success(filePath);
        } catch (IOException e) {
            return ResultUtil.error(-1, "图片上传失败。");
        }

    }

    // 获取报警信息
    @RequestMapping(value = "/alarmlist")
    public Msg alarmList(@RequestBody Map<String, Object> reqMap) {
        int page = Integer.parseInt(reqMap.get("page").toString());
        int rows = Integer.parseInt(reqMap.get("row").toString());
        int gc_id = 0;
        int alarmType = Integer.parseInt(reqMap.get("alarmType").toString());
        int alarmStat = Integer.parseInt(reqMap.get("alarmStat").toString());
        String start = reqMap.get("start").toString();
        String end = reqMap.get("end").toString();
        int smkBuildingId = Integer.parseInt(reqMap.get("smkBuildingId").toString());

        String openid = getLoginName();
        Map<String, Object> result = _alarmSvs.findByPageable_WX(openid, smkBuildingId, alarmType, alarmStat, start,
                end, gc_id, page, rows);
        return ResultUtil.success(result);
    }

    // 解除报警
    @PostMapping(value = "/relievealarm")
    public Msg relieveAlarm(@RequestBody Map<String, Object> map) {
        Integer id = Integer.valueOf(String.valueOf(map.get("id")));
        Integer dealMethod = Integer.valueOf(String.valueOf(map.get("dealMethod")));
        Integer dealType = Integer.valueOf(String.valueOf(map.get("dealType")));
        String dealResult = String.valueOf(map.get("dealResult"));
        if (id == null || dealMethod == null || dealType == null || dealResult == null) {
            return ResultUtil.error(-1, "参数错误");
        }
        Smk_Alarm alarm = _alarmSvs.findOneById(id);
        alarm.setDealMethod(dealMethod);
        alarm.setDealType(dealType);
        alarm.setDealResult(dealResult);
        alarm.setAlarmStat(2);
        _alarmSvs.save(alarm);
        // HttpResult re = _apiSvs.doGetCommand(alarm.getSmkDevicesId(), "5859");
        return ResultUtil.success();
    }

    @PostMapping(value = "/unbind")
    public Msg unbind(@RequestBody Map<String, Object> map) {
        int id = Integer.valueOf(request.getAttribute("user_id").toString());
        // Smk_Buildings b =_buildSvs.findOneById(id);
        String openid = getLoginName();
        List<Smk_Buildings> shops = _buildSvs.findByOpenid(openid);
        for (Smk_Buildings b : shops) {
            if (b != null) {
                b.setWxImage("");
                b.setWxName("");
                b.setOpenid("");
                _buildSvs.save(b);
            }
        }
        return ResultUtil.success();
    }

}